<?php

class MobileController extends AppController
{
	var $name = "Mobile";
	var $layout = "mobile";
	//var $scaffold;
	
	var $uses = array("Client", "Survey", "Item", "User");
	
	function index(){
		$this->set('message', 'hi');
	}
	
	function get_survey_by_sid($id=null){
		$this->set('survey', $this->Survey->findById($id));
		$this->set('s_items', $this->Item->findAllBySurveyId($id));
	}
	
	function get_survey_text($id=null){
		$user = $this->User->findById($id);
		$data = array();
		foreach($user['Survey'] as $survey){
			if($survey['SurveysUser']['downloaded']==0){
				$data[$survey['id']] = $this->Survey->findById($survey['id']);
			}
		}
		$this->set('data', $data);
	}
	
	function get_survey($id){
		$user = $this->User->findById($id);
		$files = "../../files";
		exec("rm $files/tmp/$id.zip");
		foreach($user['Survey'] as $survey){
			if($survey['SurveysUser']['downloaded']==0){
				$s_id = $survey['SurveysUser']['survey_id'];
				$u_id = $survey['SurveysUser']['user_id'];
				$this->Survey->query("UPDATE surveys_users SET downloaded=1 WHERE survey_id=$s_id and user_id=$u_id;");
				exec("zip -j $files/tmp/$id.zip $files/$survey[id]/$survey[id].zip");
			}
		}
		$this->redirect("http://steroid.trombonium.net/tmp/$id.zip");
		//$this->set('data', $user);
	}
	
	function post_results($u_id){
		$files = "../../files";
		$s_id = substr($_FILES['resultsfile']['name'], 0, strpos($_FILES['resultsfile']['name'], ".zip"));
		exec("mkdir $files/$s_id/$u_id");
		exec("rm $files/$s_id/$u_id/sql");  //erase old update
		$zipfile = $_FILES['resultsfile']['tmp_name'];
		$unzip = shell_exec("unzip $zipfile -d $files/$s_id/$u_id");
		$sql = file_get_contents("$files/$s_id/$u_id/sql");
		$sql = str_replace('\\"', '"', $sql);
		$queries = explode("\n", $sql);
		foreach($queries as $q){
			$this->Survey->query($q);
		}   
		$this->set('files', $_FILES);
		$this->set('unzip', $unzip);
		$this->set('sql', $sql);
	}

	function zip_em_all(){
		$surveys = $this->Survey->findAll();
		foreach($surveys as $survey){
			$this->Survey->zip_it($survey['Survey']['id']);
		}
	}
	
	function test_upload(){
		$this->set('post', $_POST);
		$this->set('files', $_FILES);
	}
	
	function beforeFilter()
	{
		$this->Auth->allow('*');
	}
	
}

?>
